from sqlalchemy.ext.asyncio import AsyncSession as Session
from app.services.redis_service import redis_get, redis_set
from app.crud.waveup.wp_collection import get_collection_by_product_id
from app.core.logger import logger
import json
from app.services.xm_service import archive_market
from pydantic import BaseModel, Field
from app.core.config import settings
from app.core.constants import ThirdPartner
from app.crud.uc.partner_token import get_partner_token

class archiveBrief(BaseModel):
    archiveId: int
    platformId: int

"""
NFT藏品服务
通过waveup产品ID查询XM平台藏品行情信息
"""
async def get_archive_ids(
    session: Session,
    productId: str,
):
    """根据waveup产品ID获取XM藏品ID"""
    # 先从Redis缓存中获取
    archive = await redis_get(f"xm_archive_ids:{productId}")
    if archive:
        return json.loads(archive)
    # 从本地数据库查询
    collection = await get_collection_by_product_id(session, productId)
    if not collection:
        logger.error(f"XM藏品 {productId} 不存在")
        return None
    
    archive = archiveBrief(archiveId=collection.archiveId, platformId=collection.platformId)
    # 缓存到Redis
    await redis_set(f"xm_archive_ids:{productId}", json.dumps(archive.model_dump()))
    return archive.model_dump()

class XmNftDetail(BaseModel):
    archiveId: int = Field(description="XM藏品ID")
    productName: str = Field(description="藏品名称")
    imageUrl: str = Field(description="藏品图片URL")
    dealCount: int = Field(description="藏品交易次数(在xm平台交易量)")
    dealCountRate: float = Field(description="藏品交易增长率(在xm平台)")
    marketAmount: float = Field(description="藏品当前市场价值(在xm平台)")
    marketAmountRate: float = Field(description="藏品市场价值增长率(在xm平台)")
    minPrice: float = Field(description="藏品最低价格(在xm平台)")
    minPriceRate: float = Field(description="藏品最低价格增长率(在xm平台)")

# 获取藏品详情
async def get_nft_detail(
    session: Session,
    productId: str,
    uid: int,
) -> dict:
    """根据waveup产品ID获取XM藏品详情"""
    # 先从Redis缓存中获取
    nft_detail = await redis_get(f"xm_nft_detail:{productId}")
    if nft_detail:
        return json.loads(nft_detail)
    
    # 从本地数据库查询
    collection = await get_collection_by_product_id(session, productId)
    if not collection:
        logger.error(f"XM藏品 {productId} 不存在")
        return None
    
    # 从XM平台查询藏品行情(archive_market)
    # 查询用户WP Token
    partner_token = await get_partner_token(
        session=session,
        uid=uid,
        partner=ThirdPartner.XMeta,
    )
    xm_res = await archive_market(xm_auth=partner_token.accessToken, archiveId=collection.archiveId)
    if not xm_res or xm_res["code"] != 200:
        logger.error(f"XM藏品 {productId} 行情查询失败: {xm_res}")
        xm_res = None
    
    # 解析XM平台返回的行情数据
    nft_detail = XmNftDetail(
        archiveId=collection.archiveId,
        productName=collection.productName,
        imageUrl=collection.imageUrl,
        dealCount=xm_res["data"]["dealCount"] if xm_res else 0,
        dealCountRate=xm_res["data"]["dealCountRate"] if xm_res else 0,
        marketAmount=xm_res["data"]["marketAmount"] if xm_res else 0,
        marketAmountRate=xm_res["data"]["marketAmountRate"] if xm_res else 0,
        minPrice=xm_res["data"]["minPrice"] if xm_res else 0,
        minPriceRate=xm_res["data"]["minPriceRate"] if xm_res else 0,
    )
    # 缓存到Redis
    await redis_set(f"xm_nft_detail:{productId}", json.dumps(nft_detail.model_dump()), settings.NFT_DETAIL_EXPIRE)
    return nft_detail.model_dump()
